# -*- encoding: utf-8 -*-
'''
@File    :   ws_client.py
y
@Time    :   2020/07/07 19:48:27
@Author  :   Wicos 
@Version :   1.0
@Contact :   wicos@wicos.cn
'''

# here put the import lib
import websocket
from threading import Timer,Thread,Event
import time


def on_message(ws, msg):
    print(msg)


def on_open(ws):
    print("opening")


def on_close(ws):
    print("closed")


def on_emit(ws):
    """
    创建心跳线程
    :param ws: object
    :type ws: websocket object
    :return: None
    :rtype: None
    """
    event = Event()
    heartbeat = HeartbeatThread(event, ws)
    heartbeat.start()


class HeartbeatThread(Thread):
    """
    心跳
    """

    def __init__(self, event, ws):
        super(HeartbeatThread, self).__init__()
        self.event = event
        self.ws = ws

    def run(self):
        while True:
            # 发送ping包
            pings = str({"ping":str(int(time.time()))}).replace("'",'"')
            self.ws.send(pings)
            self.event.wait(timeout=2)


def main_fun():
    websocket.enableTrace(False)
    ws = websocket.WebSocketApp(
        f"ws://127.0.0.1:4567",
        on_message=on_message,
        on_close=on_close,
    )
    ws.on_open = on_open
    t = Timer(20, on_emit, args=(ws,))
    t.start()
    ws.run_forever()

if __name__ == "__main__":
    main_fun()
